﻿using Microsoft.Extensions.Logging;
using ST.Common.Util;
using ST.Common.Util.Xml;
using ST.WX.Common.Exceptions;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;

namespace ST.WX.Common.Pay
{
	public class WXPayApi
	{
		private readonly ILogger logger;

		public WXPayApi(ILogger<WXPayApi> _logger)
		{
			logger = _logger;
		}

		/// <summary>
		/// 统一下单接口
		/// </summary>
		/// <param name="model"></param>
		/// <param name="key">支付密钥</param>
		/// <returns></returns>
		public WXPayUnifiedOrderRet UnifiedOrder(WXPayUnifiedOrderData model)
		{
			try
			{
				string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
				var ret = new WXPayUnifiedOrderRet();
				model.SendRequest(ret, url);
				return ret;
			}
			catch (WXPayException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (WXException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new WXException("统一下单出错", ex);
			}
		}

		/// <summary>
		/// 查询订单（如果订单超时或不存在会抛出异常）
		/// </summary>
		/// <param name="model"></param>
		/// <param name="key">支付密钥</param>
		/// <returns></returns>
		public WXPayOrderQueryRet OrderQuery(WXPayOrderQueryData model)
		{
			try
			{
				string url = "https://api.mch.weixin.qq.com/pay/orderquery";
				var ret = new WXPayOrderQueryRet();
				model.SendRequest(ret, url);
				return ret;
			}
			catch (WXPayException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (WXException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new WXException("查询订单出错", ex);
			}
		}

		/// <summary>
		/// 关闭订单
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		public WXPayCloseOrderRet CloseOrder(WXPayCloseOrderData model)
		{
			try
			{
				string url = "https://api.mch.weixin.qq.com/pay/closeorder";
				var ret = new WXPayCloseOrderRet();
				model.SendRequest(ret, url);
				return ret;
			}
			catch (WXPayException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (WXException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new WXException("关闭订单出错", ex);
			}
		}
	}
}
